<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/16
 * Time: 下午2:07
 */

namespace app\agent\controller;


use app\common\controller\CosUpload;
use app\common\controller\Manager;
use app\common\controller\Platurl;
use app\common\model\Agent;
use app\common\model\AgentSales;
use app\common\model\AuthRoleUser;
use app\common\model\CardStore;
use app\common\controller\AdminBase;
use app\common\model\ActionLog;
use app\common\model\DeviceCodeQuery;
use app\common\model\DeviceMicro;
use app\common\model\DevicePrint;
use app\common\model\LoginUsers;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\MerchantCashier;
use app\common\model\MerchantCate;
use app\common\model\MerchantContent;
use app\common\model\Prints;
use app\common\model\WxOpen;
use Bank\HuifuServer;
use think\Request;
use think\Session;
use think\Config;
use Wechat\Wxobjopen;

class Momachtest extends AdminBase
{
    public function manager()
    {
        $topmid = request()->param('top_mid');
        $Manager = new Manager();
        $data = $Manager->merchantlogin($topmid);

        if ($data['result_code'] == "SUCCESS") {
            $this->success('正在登录商户平台', '/member.php');
        } else {
            $this->error($data['result_msg']);
        }

    }

    //商户列表
    public function momachlist()
    {
        //搜索条件
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            $map['merchant_name'] = array('like', '%' . trim($p_data['merchant_name']) . '%');
        } else {
            $p_data['merchant_name'] = '';
        }
        //判断代理商/业务员
        if (Session::get('level') == '2002') {
            $AgentSales = new AgentSales();
            $map['salesman'] = $AgentSales->where('uid', Session::get('user.uid'))->value('id');
        } else {
            $map['agent'] = ['in', $this->get_agent_id()];
        }
        $Momerchant = new Momerchant();
        $momach = $Momerchant->where($map)->paginate(10, false, ['query' => request()->param()]);
        $Mercate = new MerchantCate();
        //判断代理商/业务员
        if (Session::get('level') == '2002') {
            $AgentSales = new AgentSales();
            $mab['salesman'] = $AgentSales->where('uid', Session::get('user.uid'))->value('id');
        } else {
            $mab['agent'] = ['in', $this->get_agent_id()];
        }
        $momachlist = $Momerchant->where($mab)->select();
        $map_cate['parent_id'] = 0;
        $map_cate['status'] = 0;
        $level = $Mercate->where($map_cate)->select();
        $this->assign('momachlist', $momachlist);
        $this->assign('momach', $momach);
        $this->assign('p_data', $p_data);
        $this->assign('level', $level);
        return $this->fetch();

    }

    /*
     * 删除商户
     * */
    public function momachdel()
    {
        $map['agent'] = $this->get_agent_id();
        $map['id'] = request()->get('id');
        $blog = Momerchant::get($map);
        $del = $blog->together('Merchant')->delete();
        if ($del) {
            $this->success('删除成功');
        } else {
            $this->error($blog->getError());
        }

    }

    //门店列表
    public function machlist()
    {
        //搜索条件
        $request = request();
        $p_data = $request->get();
        $top_mid = $request->param('top_mid');

        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            $map['merchant'] = array('like', '%' . trim($p_data['merchant']) . '%');
        } else {
            $p_data['merchant'] = '';
        }
        $Merchant = new Merchant();
        //判断代理商/业务员
        $LoginUsers = new LoginUsers();
        $user = $LoginUsers->where(['id' => Session::get('user.uid')])->find();
        if ($user['level'] == '2002') {
            $map['id'] = ['in', $this->get_mer_mid()];
        } else {
            $map['agent'] = ['in', $this->get_agent_id()];
        }
        $map['top_mid'] = $top_mid;
        $mach = $Merchant->where($map)->paginate(10, false, ['query' => request()->get()]);
        $Mercate = new MerchantCate();
        $map_cate['parent_id'] = 0;
        $map_cate['status'] = 0;
        $level = $Mercate->where($map_cate)->select();
        $mab['top_mid'] = $top_mid;
        $machlist = $Merchant->where($mab)->select();
        $this->assign('machlist', $machlist);
        $this->assign('p_data', $p_data);
        $this->assign('level', $level);
        $this->assign('mach', $mach);
        return $this->fetch();

    }

    //商户详情
    public function momachinfo()
    {
        $request = request();
        $param = $request->get();
        $id = $request->param('id');
        $map['id'] = $id;
        $map['agent'] = $this->get_agent_id();
        //商户
        $Momerchant = new Momerchant();
        $user = $Momerchant->where(array('id' => $param['id']))->find();
        $wxopen = WxOpen::get($user['wx_open_id']);
        $MerchantCashier = new MerchantCashier();
        $cashier = $MerchantCashier->where('top_mid', $id)->select();
        //账号
        $LoginUsers = new LoginUsers();
        $userinfo = $LoginUsers->where('top_mid', $param['id'])->find();
        $this->assign('userinfo', $userinfo);
        $this->assign('wxopen', $wxopen);
        $this->assign('cashier', $cashier);
        $this->assign('user', $user);
        //      $this->assign('czlog', $czlog);
        return $this->fetch();

    }

    //门店详情
    public function machinfo()
    {
        $request = request();
        $param = $request->get();
        $id = $request->param('id');
        $map['id'] = $id;
        $map['agent'] = $this->get_agent_id();
        $DeviceMicro = new DeviceMicro();
        $mab['mid'] = $id;
        $devicelist = $DeviceMicro->where($mab)->paginate('15', false, ['query' => request()->param()]);
        $Merchant = new Merchant();
        $user = $Merchant->where($map)->relation('MerchantContent')->find();
        $wxopen = WxOpen::get($user['wx_open_id']);
        $this->assign('wxopen', $wxopen);
        $this->assign('devicelist', $devicelist);
        $this->assign('user', $user);
        return $this->fetch();

    }

    //门店修改
    public function machxg()
    {
        $Merchant = new Merchant();
        $request = request();
        $id = $request->param('id');
        if (Request()->isAjax()) {
            $arr = $request->post();
            $map['id'] = $arr['id'];
            $map['agent'] = $this->get_agent_id();
            $data['tpl_msg_type'] = $arr['tpl_msg_type'];
            $data['start_time'] = strtotime($arr['start_time']);
            $data['end_time'] = strtotime($arr['end_time']);
            $res = $Merchant->save($data, $map);
            if ($res) {
                $arrs['code'] = 0;
                $arrs['message'] = '修改成功';
                $arrs['data'] = $data;
                $arrs['map'] = $map;
            } else {
                $arrs['code'] = 0;
                $arrs['message'] = '修改失败';
                $arrs['data'] = $data;
                $arrs['map'] = $map;
            }
            return json($arrs);
        } else {
            $map['id'] = $id;
            $map['agent'] = $this->get_agent_id();
            $DeviceMicro = new DeviceMicro();
            $mab['mid'] = $id;
            $devicelist = $DeviceMicro->where($mab)->paginate('15', false, ['query' => request()->param()]);
            $mach = $Merchant->where($map)->relation('MerchantContent')->find();
            $wxopen = WxOpen::get($mach['wx_open_id']);
            $this->assign('wxopen', $wxopen);
            $this->assign('devicelist', $devicelist);
            $this->assign('mach', $mach);
            return $this->fetch();
        }
    }

    /*
     * 获取二维码
     * */
    public function getqrcode()
    {
        $jg = action('Qrcodes/qrcode', array(request()->param('mid'), "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Index/pay/id/" . request()->param('mid') . ".html"));
        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
        exit;
    }

    /*
     * 获取门店二维码
     * */
    public function getmercode()
    {
        $map['id'] = request()->param('mid');
        $Merchant = new Merchant();
        $merchant = $Merchant->where($map)->value('merchant');
        $jg = action('Qrcodes/mercode', array(request()->param('mid'), 48, "https://" . $_SERVER['HTTP_HOST'] . "/index.php?s=/Index/pay/id/" . request()->param('mid') . ".html", $merchant));

        $qr = $jg;
        $length = filesize($qr);
        $type = mime_content_type($qr);
        $showname = ltrim(strrchr($qr, '/'), '/');
        header("Content-Description: File Transfer");
        header('Content-type: ' . $type);
        header('Content-Length:' . $length);
        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $showname . '"');
        }
        readfile($qr);
        exit;

    }


    /*
     * 添加商户
     * */
    public function addmomach()
    {
        if (Request()->isPost()) {
            $arr = request()->post();
//            file_put_contents('/data2/html/payos/test.txt', 'isuser-3:' . json_encode($arr), FILE_APPEND);
            if (strlen(trim($arr['username'])) < 6) {
                $this->error('用户名不可小于6位');
            }
            $Momerchant = new Momerchant();
            $data = $arr;
            $data['merchant_name'] = trim($arr['merchant_name']);
            $data['sub_mch_id'] = trim($arr['sub_mch_id']);
            $data['agent'] = $this->get_agent_id();
            if ($arr['img'] !== '') {
                $data['img'] = $arr['img'];
            } else {
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

                $data['img'] = $http_type . $_SERVER['HTTP_HOST'] . '/uploads/mach/default.jpg';
            }
            $categories = [$arr['leibie'] . ',' . $arr['leibie2']];
            $data['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);      //类别
            $data['addtime'] = time();
            $data['tpl_msg_type'] = $arr['tpl_msg_type'];
            //时间
            $data['start_time'] = strtotime($arr['start_time']);
            $data['end_time'] = strtotime($arr['end_time']);
            //费率
            $data['wx_service_charge'] = $arr['wx_service_charge'];
            $data['ali_service_charge'] = $arr['ali_service_charge'];
            $data['pos_service_charge'] = $arr['pos_service_charge'];

            $data['momach_type'] = $arr['momach_type'];
//            file_put_contents('/data2/html/payos/test.txt', 'isuser-4:' . json_encode($arr), FILE_APPEND);
            $add = $Momerchant->allowField(true)->validate('momerchant.add')->save($data);
            if ($add == false) {
                $this->error($Momerchant->getError(), url('momach/momachlist'));
            } else {
                $datas['username'] = trim($arr['username']);
                $datas['xingming'] = trim($arr['contacts']);
                $datas['top_mid'] = $Momerchant->id;
                $datas['level'] = 3001;
                $datas['agent'] = $this->get_agent_id();
                $datas['password'] = md5($arr['password']);
                $datas['tel'] = trim($arr['tel']);
                $datas['createtime'] = time();

                $LoginUsers = new LoginUsers();
                $res = $LoginUsers->allowField(true)->validate(true)->save($datas);
                if ($res) {
                    $sdata['role_id'] = 4;
                    $sdata['user_id'] = $LoginUsers->id;
                    $AuthRoleUser = new AuthRoleUser();
                    $AuthRoleUser->save($sdata);
                    $this->success('添加成功', 'momach/momachlist');
                } else {
                    $this->error($LoginUsers->getError());
                }
                $this->success('创建成功！', url('momach/momachlist'));
            }
        } else {
//            var_dump($this->get_agent_id());
            $AgentSales = new AgentSales();
            $MerchantCate = new MerchantCate();
            $Agent = new Agent();
            $agent_id = $this->get_agent_id();
            $agents['name'] = $Agent->where('id', $agent_id)->value('name');
            $sales = $AgentSales->where('agent', $agent_id)->select();
            $cate = $MerchantCate->where(['level' => 1])->select();
            $time['starttime'] = date("Y-m-d h:i:s", time());
            $time['endtime'] = date("Y-m-d h:i:s", strtotime("+1 year"));
            $this->assign('time', $time);
            $this->assign('sales', $sales);
            $this->assign('agents', $agents);
            $this->assign('cate', $cate);

            return $this->fetch();
        }
    }

    /*
     * 商户修改
     * */
    public function momachxg()
    {
        if (Request()->isPost()) {
            $arr = request()->post();
//            file_put_contents('/data2/html/payos/test.txt', 'isuser-1:' . json_encode($arr), FILE_APPEND);
            $categories = [$arr['leibie'] . ',' . $arr['leibie2']];
            $Momerchant = new Momerchant();
            $data = $arr;
            $data['sub_mch_id'] = trim($arr['sub_mch_id']);
            $data['tpl_msg_type'] = $arr['tpl_msg_type'];
            $data['top_mid'] = Session::get('login_top_mid');
            $data['categories'] = json_encode($categories, JSON_UNESCAPED_UNICODE);      //类别
//            file_put_contents('/data2/html/payos/test.txt', 'isuser-2:' . json_encode($data), FILE_APPEND);
            //时间
//            $data['start_time']=strtotime($arr['start_time']);
//            $data['end_time']=strtotime($arr['end_time']);
//            $data['momach_type']= $arr['momach_type'];
            $up = $Momerchant->allowField(true)->validate('momerchant.edit')->save(
                $data, ['id' => $arr['id'], 'agent' => $this->get_agent_id()]);
            if ($up == false) {
                $this->error('修改失败！' . $Momerchant->getError(), url('momach/momachlist'));
            } else {
                $this->unbinlist($arr);
                $this->success('修改成功！', url('momach/momachlist'));
            }
        } else {
            $param = request()->param();
            $Momerchant = new Momerchant();
            $mar['agent'] = $this->get_agent_id();
            $sales = AgentSales::where($mar)->select();
            $mach = $Momerchant->where(array('id' => $param['id']))->find();
            $mach['start_time'] = date("Y-m-d", $mach['start_time']);
            $mach['end_time'] = date("Y-m-d", $mach['end_time']);
            $ali_app_id = Agent::where('id', $this->get_agent_id())->value('ali_app_id');
            $Platurl = new Platurl();
            $agent_url = $Platurl->getagenturl('agent_id', $this->get_agent_id());
            if ($ali_app_id) {
                $surl = "https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=" . $ali_app_id . "&redirect_uri=" . $agent_url . "/index.php?s=/wxauth/aliauth/merchid/" . $mach['id'];
                $jg = action('Qrcodes/sq_qrcode', array($mach['id'], $surl));

            } else {
                $surl = "";
                $jg = "";
            }
            $MerchantCate = new MerchantCate();
            $cate = $MerchantCate->where(['level' => 1])->select();
            $this->assign('surl', $surl);
            $this->assign('qrcode', $jg);
            $this->assign('sales', $sales);
            $this->assign('mach', $mach);
            $this->assign('cate', $cate);
            return $this->fetch();
        }
    }

    //商户进价
    public function momachbid(Request $request)
    {
        if ($request->isAjax()) {

        } else {
            return $this->fetch();
        }

    }

    public function machtobank(Request $request)
    {

        if ($request->isAjax()) {
            $param = $request->post();
            if ($param) {
                $JsonData['merchClass'] = $param['merchClass'];//商户性质 企业 个体
                $JsonData['merchType'] = $param['merchType'];//商户类型 连锁 单店
                if ($param['merchType'] == 1) {
                    $JsonData['relatedMerchName'] = $param['relatedMerchName'];//连锁商户主商户号
                }
                $JsonData['merchName'] = $param['merchName'];//商户名称
                $JsonData['merchShortName'] = $param['merchShortName'];//商户简称
                $JsonData['userDefinedName'] = $param['merchShortName'];
                $JsonData['regProvId'] = $param['regProvId'];
                $JsonData['regCityId'] = $param['regCityId'];
                $JsonData['regAreaId'] = $param['regAreaId'];
                $JsonData['regAddr'] = $param['regAddr'];
                $JsonData['provId'] = $param['regProvId'];
                $JsonData['cityId'] = $param['regCityId'];
                $JsonData['areaId'] = $param['regAreaId'];
                $JsonData['merchAddr'] = $param['regAddr'];
                $JsonData['businessShours'] = "09:00";
                $JsonData['businessEhours'] = "22:00";
                $JsonData['isCreditCode'] = $param['isCreditCode'];//是否三证合一
                if ($param['isCreditCode'] == 1) {
                    $JsonData['creditCode'] = $param['creditCode'];//统一社会信用代码证编号
                } else {
                    $JsonData['regCode'] = $param['regCode'];//营业执照编号
                    $JsonData['orgCode'] = $param['orgCode'];//组织机构代码证编号
                }
                $JsonData['licType'] = $param['licType'];//证件有效期类型
                $JsonData['licSdate'] = $param['licSdate'];//
                if ($param['licType'] == 1) {
                    $JsonData['licEdate'] = $param['licEdate'];
                }
                $JsonData['cateType'] = $param['cateType'];//商户经营类型 1实体 2虚拟
                if ($param['merchClass'] == 1) {
                    $JsonData['legalName'] = $param['contactName'];
                    $JsonData['idType'] = $param['contactIdType'];
                    $JsonData['idNo'] = $param['contactIdNo'];
                    $JsonData['idValidType'] = $param['contactIdValidType'];
                    $JsonData['idSdate'] = $param['contactIdSdate'];
                    if ($param['contactIdValidType'] == 1) {
                        $JsonData['idEdate'] = $param['contactIdEdate'];
                    }
                }
                $JsonData['contactName'] = $param['contactName'];
                $JsonData['contactIdType'] = $param['contactIdType'];
                $JsonData['contactIdNo'] = $param['contactIdNo'];
                $JsonData['contactIdValidType'] = $param['contactIdValidType'];
                $JsonData['contactIdSdate'] = $param['contactIdSdate'];
                if ($param['contactIdValidType'] == 1) {
                    $JsonData['contactIdEdate'] = $param['contactIdEdate'];
                }
                $JsonData['contactTelno'] = $param['contactTelno'];
                $JsonData['contactEmail'] = $param['contactEmail'];
                $JsonData['contractNum'] = "wn-" . date('Ymd') . rand(100, 300);
                $JsonData['signName'] = 18903725210;
                $JsonData['signDate'] = date('Ymd');
                $JsonData['signSdate'] = date('Ymd');
                $JsonData['signEdate'] = date('Ymd', strtotime('+1year'));
                $JsonData['tellerId'] = $param['tellerId'];;
                $JsonData['isSendMes'] = $param['isSendMes'];;
                $JsonData['isPrivate'] = $param['isPrivate'];;
                $JsonData['bankActName'] = $param['bankActName'];;
                $JsonData['bankActId'] = $param['bankActId'];;
                $JsonData['bankProvId'] = $param['bankProvId'];;
                $JsonData['bankCityId'] = $param['bankCityId'];;
                $JsonData['bankAreaId'] = $param['bankAreaId'];;
                $JsonData['bankName'] = $param['bankName'];;
                $JsonData['settleTerm'] = 2;
                $JsonData['fee01'] = $param['fee01'];
                if ($param['isPrivate'] == 1) {
                    $JsonData['accountIdType'] = $param['accountIdType'];
                    $JsonData['accountIdNo'] = $param['accountIdNo'];
                    $JsonData['accountIdValidType'] = $param['accountIdValidType'];
                    $JsonData['accountIdSdate'] = $param['accountIdSdate'];
                    if ($param['accountIdValidType'] == 1) {
                        $JsonData['accountIdEdate'] = $param['accountIdEdate'];

                    }

                }
                $JsonData['auth23'] = 0;
                $JsonData['auth24'] = 0;
                //微信配置
                $JsonData['auth18'] = $param['auth18'];
                if ($param['auth18'] == 1) {
                    $JsonData['wechatCateCode'] = $param['wechatCateCode'];
                    $JsonData['fee08'] = $param['fee08'];
                    $JsonData['isMerWechat'] = 0;
                }
                //阿里配置
                $JsonData['auth19'] = $param['auth19'];;
                if ($param['auth19'] == 1) {
                    $JsonData['alipayCateCode'] = $param['alipayCateCode'];;
                    $JsonData['fee12'] = $param['fee12'];
                }
                $JsonData['bgRetUrl'] = urlencode("https://os.wunengkeji.com/huifunotify.php/");
                $JsonData['reqSerialNum'] = "wn_join-".date('YmdHis').rand(100,999);;
                $JsonData['pnrpayMerType'] = $param['pnrpayMerType'];;
                $JsonData['picUploadWay'] = "01";;
                $JsonData['memberId'] = "310000015000064160";//代理商会员号
                $JsonData['opTellerId'] = "18903725210";//代理商编号
                $JsonData['archFlph01'] = $param['archFlph01'];//营业执照
                $JsonData['archFlph04'] = $param['archFlph04'];//开户许可证
                $JsonData['archFlph05'] = $param['archFlph05'];//法人身份证
                $JsonData['archFlph06'] = $param['archFlph06'];//代理商操作员号
                $JsonData3 = json_encode($JsonData, JSON_UNESCAPED_UNICODE);
                $HuifuServer = new HuifuServer();
                $salt = "chinapnr";
                $ss2 = hash("sha256", $JsonData3 . $salt);
                $data['checkValue'] = $ss2;
                $data['jsonData'] = $JsonData3;
//                return json($data);
                $res = $HuifuServer->mch_join($data);
                if ($res['respCode'] == "0001") {
                    $re_param['result_code'] = "SUCCESS";
                    $re_param['result_msg'] = $res['respMsg'];
                    $re_param['info'] = $res['jsonData'];
                } else {
                    $re_param['result_code'] = "FAIL";
                    $re_param['result_msg'] = $res['respMsg'];
                }
                return json($re_param);
            } else {

                $method = isset($_GET['method']) ? $_GET['method'] : 'get';
                $pathname = isset($_GET['pathname']) ? $_GET['pathname'] : '/';
                $CosUpload = new CosUpload();
                $res = $CosUpload->gettemkey($method, $pathname);
                return json($res);
            }
        } else {
            return $this->fetch();
        }


    }

    //
    private function unbinlist($momach)
    {
        if ($momach) {
            $Momerchant = new Momerchant();
            $Merchant = new Merchant();
            $LoginUsers = new LoginUsers();
            $machtpl_type = $Momerchant->where(['id' => $momach['id']])->value('tpl_msg_type');
            $Merchant->save(['tpl_msg_type' => $machtpl_type], ['top_mid' => $momach['id']]);
            //门店通知类型END
            $midlist = $Merchant->where(['top_mid' => $momach['id']])->field('id')->select();
            $smid = [];
            foreach ($midlist as $k => $v) {
                $smid[] = $v['id'];
            }
            //门店IDEND
            if ($midlist) {
                $smerid = $smid;
                $len = count($smerid);
                if ($len > 1) {
                    foreach ($smerid as $k => $v) {
                        $msid[] = array(array('like', '%,' . $v), array('like', $v . ',%'), array('like', '%,' . $v . ',%'), array('eq', $v), 'or');
                    }
                    $map['mid'] = array($msid, 'or');
                } else {
                    $map['mid'] = $smerid[0];
                }
            } else {
                $map['mid'] = 0;
            }
            $userlist = $LoginUsers->where($map)->select();
            //商户用户END
            foreach ($userlist as $k => $v) {
                if ($v['tpl_msg_type'] !== $machtpl_type) {
                    $data[$k]['id'] = $v['id'];
                    $data[$k]['openid'] = '';
                    $data[$k]['headimg'] = '';
                    $data[$k]['nickname'] = '';
                    $data[$k]['tpl_msg_type'] = $machtpl_type;
                }
            }
            if (isset($data)) {
                $res = $LoginUsers->saveAll($data);
                foreach ($data as $k => $v) {
                    $mab[] = $v['id'];
                }
                $MerchantCashier = new MerchantCashier();
                $ress = $MerchantCashier->where(['uid' => ['in', $mab]])->delete();
                //收银员通知END
            }
        }
    }

    public function getmid($param)
    {
        $Merchant = new Merchant();
        $midlist = $Merchant->where(['top_mid' => $param['id']])->field('id')->select();
        $smid = [];
        foreach ($midlist as $k => $v) {
            $smid[] = $v['id'];
        }
        $mid = implode(',', $smid);
        return $mid;
    }

    //重置密码
    public function resetpassword()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $LoginUsers = new LoginUsers();

            $password = $this->getrandmopassword(8);
            $data['password'] = MD5($password);
            $map['top_mid'] = $arr['id'];
            $map['level'] = 3001;
            $res = $LoginUsers->allowField(true)->save($data, $map);
            if ($res) {
                $rarr['code'] = 0;
                $rarr['message'] = '重置成功';
                $rarr['username'] = $LoginUsers->where($map)->value('username');
                $rarr['new_password'] = $password;
            } else {
                $rarr['code'] = 9001;
                $rarr['message'] = '重置失败';
            }
            return json($rarr);
        }
    }

    //生成随机密码
    private function getrandmopassword($len, $chars = null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }


    //商户设备管理
    public function momachdevicegl(Request $request)
    {
        if ($request->isAjax()) {
            $DeviceCodeQuery = new DeviceCodeQuery();
            $param = $request->post();
            if (!empty($param['top_mid'])) {
                $map['a.top_mid'] = $param['top_mid'];
            }
            if (!empty($param['status'])) {
                $map['a.status'] = $param['status'];
            }
            $map['a.agentid'] = $this->get_agent_id();
            $list = $DeviceCodeQuery->alias('a')
                ->join('wn_momerchant b', 'a.top_mid=b.id', 'left')
                ->field('a.id,a.top_mid,a.agentid,a.code,a.status,a.addtime,b.merchant_name')
                ->where($map)->select();
            $re_param["total"] = $DeviceCodeQuery->alias('a')->where($map)->count();
            $lists = [];
            foreach ($list as $k => $v) {
                $lists[$k] = $v;
                $lists[$k]['status'] = $v['status'] == 1 ? '未确认' : '已确认';
                $lists[$k]['addtime'] = date('Y-m-d h:i:s', $v['addtime']);
            }
            //获取的记录
            $re_param["rows"] = $lists;
            return json($re_param);
        } else {
            $param = $request->param();
            $this->assign('info', $param);
            $Momerchant = new Momerchant();
            $mapm['agent'] = ['in', $this->get_agent_id()];
            $momach = $Momerchant->where($mapm)->field('id,merchant_name')->select();
            $this->assign('momach', $momach);
            return $this->fetch();
        }
    }

    public function getmomachlist(Request $request)
    {
        if ($request->isAjax()) {
            $Momerchant = new Momerchant();
            if (!empty($param['merchant_name'])) {
                $map['merchant_name'] = ['like', '%' . $param['merchant_name'] . '%'];
            }
            $map['agent'] = $this->get_agent_id();
            $list = $Momerchant->where($map)->select();
            //获取的记录
            $re_param["total"] = $Momerchant->where($map)->field('id,merchant_name')->count();
            $re_param["rows"] = collection($list)->toArray();
            return json($re_param);
        }
    }

    //商户设备管理
    public function momachdevicegllist(Request $request)
    {
        if ($request->isAjax()) {
            $DeviceCodeQuery = new DeviceCodeQuery();
            $param = $request->post();
            if (!empty($param['top_mid'])) {
                $map['a.top_mid'] = ['in', $param['top_mid']];
            }
            if (!empty($param['status'])) {
                $map['a.status'] = $param['status'];
            }
            $map['a.agentid'] = $this->get_agent_id();
            $list = $DeviceCodeQuery->alias('a')
                ->join('wn_momerchant b', 'a.top_mid=b.id', 'left')
                ->field('a.id,a.top_mid,a.agentid,a.code,a.status,a.addtime,b.merchant_name')
                ->where($map)->select();
            $re_param["total"] = $DeviceCodeQuery->alias('a')->where($map)->count();
            $lists = [];
            foreach ($list as $k => $v) {
                $lists[$k] = $v;
                $lists[$k]['status'] = $v['status'] == 1 ? '未确认' : '已确认';
                $lists[$k]['addtime'] = date('Y-m-d h:i:s', $v['addtime']);
            }
            //获取的记录
            $re_param["rows"] = $lists;
            $re_param["map"] = json_encode($map);
            return json($re_param);
        } else {
            $Momerchant = new Momerchant();
            $mapm['agent'] = ['in', $this->get_agent_id()];
            $momach = $Momerchant->where($mapm)->field('id,merchant_name')->select();
            $this->assign('momach', $momach);
            return $this->fetch();
        }
    }

    //设备操作
    public function momachappstatu(Request $request)
    {
        if ($request->isAjax()) {
            $param = $request->post();
            $DeviceCodeQuery = new DeviceCodeQuery();
            $map['id'] = $param['id'];
            $map['agentid'] = $this->get_agent_id();
            $ress = $DeviceCodeQuery->where($map)->find();
            $data['status'] = $ress['status'] == 1 ? 2 : 1;
            $res = $DeviceCodeQuery->save($data, $map);
            if ($res) {
                $rarr['code'] = 0;
                $rarr['message'] = '操作成功';
            } else {
                $rarr['code'] = 9001;
                $rarr['message'] = '操作失败';
            }
            return json($rarr);
        }
    }


    /*
     * 设备列表显示
     * */
    public function device_micro_view()
    {
        if (request()->isAjax()) {
            $map['mid'] = request()->post('mid');
            $list = DeviceMicro::where($map)->select();
            return json($list);
        }
    }

    public function getmomerchs()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $ali_mer_id = Momerchant::where($map)->value('ali_merid');
            if ($ali_mer_id) {
                $data = array('code' => 0, 'ali_merid' => $ali_mer_id, 'message' => "获取成功");
            } else {
                $data = array('code' => 1, 'message' => "获取失败");
            }
            return json($data);


        }


    }

    /*
     * 修改退款密码
     * */
    public function device_micro_md_pass()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $data['tk_pass'] = MD5(request()->post('tk_pass'));
            $DeviceMirco = new DeviceMicro();
            $sa = $DeviceMirco->save($data, $map);
            if ($sa) {
                $arr = array('code' => 0, 'message' => "退款密码修改成功");
            } else {
                $arr = array('code' => 1, 'message' => "退款密码修改失败");
            }
            return json($arr);
        }
    }

    /*
     * 设备解绑
     * */
    public function device_mirco_jb()
    {
        if (request()->isAjax()) {
            $map['id'] = request()->post('id');
            $data['device_code'] = null;
            $data['status'] = 0;
            $DeviceMirco = new DeviceMicro();
            $sa = $DeviceMirco->save($data, $map);
            if ($sa) {
                $arr = array('code' => 0, 'message' => "解绑设备成功");
            } else {
                $arr = array('code' => 1, 'message' => "解绑设备失败");
            }
            return json($arr);
        }
    }

    /*
     * 删除设备
     * */
    public function del_device_mirco()
    {
        if (request()->isAjax()) {
            $data['mid'] = array('in', $this->get_mer_mid());
            $data['id'] = request()->post('id');
            $del = DeviceMicro::where($data)->delete();
            if ($del) {
                $arr = array('code' => 0, 'message' => "删除成功");
            } else {
                $arr = array('code' => 1, 'message' => "删除失败");
            }
            return json($arr);

        }


    }

    /*
     * 添加设备
     * */
    public function add_device_micro()
    {
        if (request()->isAjax()) {
            $data['mid'] = request()->post('mid');
            $data['device_name'] = request()->post('device_name');
            $data['code'] = action('common/pub/generate_code');
            $data['is_tk'] = request()->post('is_tk');
            $data['tk_pass'] = MD5(request()->post('tk_pass'));
            $DeviceMirco = new DeviceMicro();
            $save = $DeviceMirco->save($data);
            if ($save) {
                $arr = array('code' => 0, 'message' => '添加成功');
            } else {
                $arr = array('code' => 1, 'message' => '添加失败');
            }
            return json($arr);
        }
    }

    /*
     * 打开授权
     * */
    public function open_auth()
    {

        $request = request();
        $System = new \app\common\model\System();
        $config = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],

        );;
        $weObj = new Wxobjopen($options);
        $pre_auth_code = $weObj->get_pre_auth_code();

        if (!$request->get('auth_code')) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $callback = $http_type . $_SERVER['HTTP_HOST'] . url("momach/open_auth", $_GET);

            $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" . $config['component_appid'] . "&pre_auth_code=" . $pre_auth_code . "&redirect_uri=" . $callback;
            header("Location: $url");
            exit();
        } else {


            $appinfo = $weObj->authorization_info($request->get('auth_code'));
            $auth_appid = $appinfo['authorization_info']['authorizer_appid'];
            $auther['component_appid'] = $config['component_appid'];
            $auther['authorizer_appid'] = $auth_appid;

            $auther_info = $weObj->get_auther_info($auther);

            if ($auther_info['authorizer_info']['service_type_info']['id'] == 2 && ($auther_info['authorizer_info']['verify_type_info']['id'] == 0 || $auther_info['authorizer_info']['verify_type_info']['id'] == 3)) {
                $data['gh_nick_name'] = $auther_info['authorizer_info']['nick_name'];
                $data['service_type_info'] = $auther_info['authorizer_info']['service_type_info']['id'];
                $data['verify_type_info'] = $auther_info['authorizer_info']['verify_type_info']['id'];
                $data['gh_id'] = $auther_info['authorizer_info']['user_name'];
                $data['alias'] = $auther_info['authorizer_info']['alias'];
                $data['qrcode_url'] = $auther_info['authorizer_info']['qrcode_url'];
                $data['principal_name'] = $auther_info['authorizer_info']['principal_name'];
                $data['wx_open_info'] = json_encode($auther_info, JSON_UNESCAPED_UNICODE);

                $data['authorizer_appid'] = $auth_appid;
                $data['authorizer_refresh_token'] = $appinfo['authorization_info']['authorizer_refresh_token'];
                $data['at_access_token'] = $appinfo['authorization_info']['authorizer_access_token'];
                $data['at_addtime'] = time();
                $data['at_expires_in'] = 7000;
                $data['addtime'] = time();
                $data['zt'] = 1;
                $func_info = "";
                foreach ($appinfo['authorization_info']['func_info'] as $k => $v) {
                    $func_info .= $v['funcscope_category']['id'] . ',';
                }
                $WxOpen = new WxOpen();
                $data['func_info'] = $func_info;
                $wx_open = $WxOpen->where(array('authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']))->find();
                if ($wx_open) {
                    $sj = $WxOpen->save($data, ['authorizer_appid' => $appinfo['authorization_info']['authorizer_appid']]);
                    $da2['wx_open_id'] = $wx_open['id'];
                } else {
                    $sj = $WxOpen->save($data);
                    $da2['wx_open_id'] = $WxOpen->id;
                }
                $da2['auth_type'] = 1;
                $mss['id'] = request()->param('id');
                $Merchant = new Momerchant();
                $Merchant->save($da2, $mss);
                if ($sj) {

                    $this->success('授权成功', url("momach/momachinfo") . "?id=" . request()->param('id'));
                } else {
                    $this->error('授权失败');
                }
            } else {
                $this->error('该公众号为订阅号或者未通过微信认证，请确认后重新授权');
            }

        }
    }

    //删除门店
    public function delmach()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            //     return json($arr);

            $map['id'] = $arr['id'];
            $map['agent'] = $this->get_agent_id();
            $Merchant = new Merchant();
            $res = $Merchant->where($map)->delete();
            if ($res) {
                $data = [
                    'code' => '0',
                    'message' => '删除成功！'
                ];
            } else {
                $data = [
                    'code' => '9001',
                    'message' => '删除失败！'
                ];
            }
        } else {
            $data = [
                'code' => '9999',
                'message' => '您没有权限处理该商户！'
            ];
        }
        return json($data);

    }


    /*
     * 获取门店列表
     * */
    public function getmachlist()
    {
        if (Request()->isAjax()) {
            $Merchant = new Merchant();
            //        $mid = $this->get_mer_mid();
            //判断代理商/业务员
            $LoginUsers = new LoginUsers();
            $user = $LoginUsers->where(['id' => Session::get('user.uid')])->find();
            if ($user['level'] == '2002') {
                $map['id'] = ['in', $this->get_mer_mid()];
            } else {
                $map['agent'] = ['in', $this->get_agent_id()];
            }
            $list = $Merchant->where($map)->paginate('10');
            return json($list);
        }

    }

    /*
     * 获取门店列表
     * 微信官方
     * */
    public function getstorelist()
    {
        if (Request()->isAjax()) {
            $CardStore = new CardStore();
            $top_mid = Session::get('login_top_mid');
            $map['top_mid'] = array('in', $top_mid);
            $list = $CardStore->where($map)->paginate('10');
            if ($list == false) {
                $data['code'] = 9001;
                $data['list'] = 0;
            } else {
                if (empty($list)) {
                    $data['code'] = 9002;
                    $data['list'] = 0;
                } else {
                    $data['code'] = 0;
                    $data['list'] = $list;
                }
            }
            return json($data);
        }

    }

    //添加打印机
    /*
     *
     * */
    public function addprint()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            if ($this->get_qx_mid($arr['mid'])) {
                //       return json($arr);
                $rules = $this->validate($arr, ['username' => 'require', 'ukey' => 'require', 'sn' => 'require']);
                if (true !== $rules) {
                    // 验证失败 输出错误信息
                    dump($rules);
                } else {
                    $sarr = Session::get('user');
                    $DevicePrint = new DevicePrint();
                    $arrs['username'] = $arr['username'];
                    $arrs['ukey'] = $arr['ukey'];
                    $arrs['sbname'] = $arr['sbname'];
                    $arrs['sn'] = $arr['sn'];
                    $arrs['mid'] = $arr['mid'];
                    $arrs['addtime'] = time();
                    $arrs['adduser'] = $sarr['nickname'];
                    $arrs['leixing'] = 'print';
                    //        return json($arrs);
                    $res = $DevicePrint->save($arrs);
                    if ($res) {
                        $data['code'] = '0';
                        $data['message'] = '添加成功！';
                    } else {
                        $data['code'] = '9001';
                        $data['message'] = '添加失败！';
                    }

                }
            } else {
                $data['code'] = '9999';
                $data['message'] = '您没有权限处理该商户！';
            }
            return json($data);
        }
    }

    //打印机列表
    public function listprint()
    {
        if (Request()->isAjax()) {
            $map['mid'] = request()->post('id');
            $DevicePrint = new DevicePrint();
            $printlist = $DevicePrint->where($map)->select();
            if ($printlist) {
                $this->assign('list', $printlist);
                return $this->fetch();
            }
        }
    }

    //删除打印机
    public function delprint()
    {
        if (Request()->isAjax()) {
            $id = request()->post('id');
            $map['id'] = $id;
            $DevicePrint = new DevicePrint();
            $res = $DevicePrint->where($map)->delete();
            if ($res) {
                $data['code'] = '0';
                $data['message'] = '移除成功！';
            } else {
                $data['code'] = '9001';
                $data['message'] = '移除失败！';
            }
            return json($data);
        }
    }

    //获取坐标地址
    public function getaddress()
    {
        if (Request()->isAjax()) {
            $arrp = request()->post();

            $location = $arrp['lat'] . ',' . $arrp['lng'];
            $data = [
                'location' => $location,
                'get_poi' => '0',
                'key' => 'KNPBZ-RXKWI-SJJGI-5S3HH-AGDS6-Q6BDW'
            ];
            $res = $this->getWsLocation($data);
            if ($res['status'] == 0) {
                $result = $res['result'];
                return json($result);
            } else {
                return json(01);
            }

        }
    }

    /*
     * 坐标地址请求
     * */
    public function getWsLocation($data)
    {
        $url = 'http://apis.map.qq.com/ws/geocoder/v1?location=' . $data['location'] . '&key=' . $data['key'] . '&get_poi=' . $data['get_poi'];
        $result = $this->http_get($url);
        return json_decode($result, true);
    }


    /*
     * get函数
     * */
    private function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /*
     * 二级分类
     *
     *
     */

    public function getsubcate()
    {
        $param = request()->post();
        $MerchantCate = new MerchantCate();
        $name = $MerchantCate->where(['parent_id' => $param['id']])->select();
        if ($name) {
            $rarr['code'] = '0';
            $rarr['data'] = $name;
            $rarr['message'] = 'success';
        } else {
            $rarr['code'] = '0';
            $rarr['data'] = '';
            $rarr['message'] = 'error';
        }
        return json($rarr);
    }
}